package com.customview.CustomUsmileCircleBar;


import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.graphics.Typeface;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.customview.R;


public class UsmileCirlcleBar extends View implements View.OnClickListener {

    Paint mRadarPaint;

    // 弧度的宽度
    int mBarWidth = 20;
    float TextHeight = 0;
    int BarBgColor = Color.WHITE;


    String sorce = "";
    String sorceLabel = "分";
    String defaultLabel = "上次刷牙得分";
    Paint mTextPaint;

    float currentDegress ;//当前角度
    float currentSorce ;//当前分数
    float maxDegress = 220f;
    int mRadius = 0;
    int DefaultDegress = 160;
    int mRadarMargin = dipToPx(getContext(), 3);


    int DefWidth = dipToPx(getContext(), 240);
    int DefHeight = dipToPx(getContext(), 120);


    Paint mBarBgPaint;
    Paint mBarPaint;
    private String TAG = getClass().getName();

    public UsmileCirlcleBar(Context context) {
        this(context, null);
    }

    public UsmileCirlcleBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public UsmileCirlcleBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mAttr(context, attrs, defStyleAttr);
    }


    float SorceSize;
    float SorceLableSize;
    float DefaultLableSize;
    String DefaultLable = "上次刷牙得分";

    Paint mLittleCirlcePaint;
    int mLittleRadius;
    //获取属性
    private void mAttr(Context context, AttributeSet attrs, int defStyleAttr) {

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.UsmileCircleBar, defStyleAttr, 0);
        SorceSize = typedArray.getDimension(R.styleable.UsmileCircleBar_mSorceSize, 72);
        SorceLableSize = typedArray.getDimension(R.styleable.UsmileCircleBar_mSorceLableSize, 42);
        DefaultLableSize = typedArray.getDimension(R.styleable.UsmileCircleBar_DefaultLableSize, 42);
        DefaultLable = typedArray.getString(R.styleable.UsmileCircleBar_DefaultLabe);


    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        init();

    }


    private void init() {

        mRadarPaint = new Paint();
        mRadarPaint.setStyle(Paint.Style.FILL);
        mRadarPaint.setStrokeWidth(20);
        mRadarPaint.setAntiAlias(true);

        mBarBgPaint = new Paint();
        mBarBgPaint.setStyle(Paint.Style.STROKE);
        mBarBgPaint.setStrokeWidth(mBarWidth);
        mBarBgPaint.setStrokeCap(Paint.Cap.ROUND);
        mBarBgPaint.setColor(BarBgColor);
        mBarBgPaint.setAntiAlias(true);
        mBarBgPaint.setAlpha(50);

        mBarPaint = new Paint();
        mBarPaint.setColor(Color.BLUE);
        mBarPaint.setStyle(Paint.Style.STROKE);
        mBarPaint.setStrokeWidth(mBarWidth);
        mBarPaint.setAntiAlias(true);

        mBarPaint.setStrokeCap(Paint.Cap.ROUND);
        mTextPaint = new Paint();

        mLittleCirlcePaint=new Paint();
        mLittleCirlcePaint.setStyle(Paint.Style.FILL);
        setLayerType(View.LAYER_TYPE_SOFTWARE,mLittleCirlcePaint);

        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setAntiAlias(true);
        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        TextHeight = (fontMetrics.bottom - fontMetrics.top) / 2;


        try {
/*            Uri uri=Uri.parse("android:resource://"+getContext().getPackageName()+"/"+R.font.alibaba_puhuiti_medium);
            mTextPaint.setTypeface(Typeface.createFromFile(uri.getPath()));*/

            mTextPaint.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "font/alibaba_puhuiti_medium.otf"));
        } catch (Exception e) {
            e.printStackTrace();
        }


        //宽高 最短 的作为 直径
        mRadius = Math.min(getWidth() / 2, getHeight()/2);
        mLittleRadius= (int) (mRadius*0.5);
        setOnClickListener(this);

        //测试
        setValues(80, true);


    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeWith = MeasureSpec.getSize(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

        //根据模式来 决定宽度
        switch (modeWidth) {

            case MeasureSpec.EXACTLY://match_parent  精确的度数
                DefWidth = sizeWith;
                break;
            case MeasureSpec.AT_MOST://wrap_content  适配的度数


                break;
        }


        //根据模式来 决定宽度
        switch (modeHeight) {

            case MeasureSpec.EXACTLY://match_parent  精确的度数
                DefHeight = sizeHeight;
                break;
            case MeasureSpec.AT_MOST://wrap_content  适配的度数


                break;
        }


        setMeasuredDimension(DefWidth, DefHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        drawBarBg(canvas);
        drawBar(canvas);
        drawRadar(canvas);
        drawLittelCirle(canvas);
        drawText(canvas);


    }


    private void drawLittelCirle(Canvas canvas) {



        canvas.save();
        canvas.translate(getWidth() / 2, getHeight()/2);
        mLittleCirlcePaint.setColor(Color.parseColor("#393948"));
        mLittleCirlcePaint.setMaskFilter(new BlurMaskFilter(mLittleRadius*0.1f, BlurMaskFilter.Blur.SOLID));

        canvas.drawCircle(0,0,mLittleRadius,mLittleCirlcePaint);

        mLittleCirlcePaint.setColor(Color.parseColor("#2F2F3A"));
        mLittleCirlcePaint.setMaskFilter(new BlurMaskFilter(mLittleRadius*0.1f, BlurMaskFilter.Blur.OUTER));
        canvas.drawCircle(0,0,mLittleRadius,mLittleCirlcePaint);
        canvas.restore();
    }


    //字体
    private void drawText(Canvas canvas) {
        canvas.save();
        canvas.translate(getWidth() / 2, getHeight()/2);

        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setTextSize(SorceSize);
        TextHeight = (mTextPaint.getFontMetrics().bottom - mTextPaint.getFontMetrics().top) / 2;

        sorce= ((int) currentSorce)+"";

        //分数
        mTextPaint.setTypeface(Typeface.createFromAsset(getContext().getAssets(),"font/alibaba_puhuiti_medium.otf"));
        mTextPaint.setAlpha(255);

        canvas.drawText(sorce, 0,  0, mTextPaint);
        //分标签
        float soreceStrWidth = mTextPaint.measureText(sorce);
        mTextPaint.setTextAlign(Paint.Align.LEFT);
        mTextPaint.setAlpha(201);
        mTextPaint.setTypeface(Typeface.createFromAsset(getContext().getAssets(),"font/alibaba_puhuiti_regular.otf"));
        mTextPaint.setTextSize(SorceLableSize);

        canvas.drawText(sorceLabel, soreceStrWidth / 2, 0, mTextPaint);
        //上次刷牙得分
        TextHeight = (mTextPaint.getFontMetrics().bottom - mTextPaint.getFontMetrics().top) / 2;
        mTextPaint.setTypeface(Typeface.createFromAsset(getContext().getAssets(),"font/alibaba_puhuiti_regular.otf"));
        mTextPaint.setAlpha(153);

        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setTextSize(DefaultLableSize);
        canvas.drawText(defaultLabel, 0, TextHeight*2, mTextPaint);
        canvas.restore();
    }


    //当前进度
    private void drawBar(Canvas canvas) {
        canvas.save();
        canvas.translate(getWidth() / 2, getHeight()/2);
        RectF mRectf = new RectF(-mRadius + mBarWidth / 2, -mRadius + mBarWidth / 2, mRadius - mBarWidth / 2, mRadius - mBarWidth / 2);
        mBarPaint.setShader(new LinearGradient(-mRadius+mBarWidth/2,0,mRadius-mBarWidth/2,0,new int[]{0xFFBC60C4,0xFF5C63FA},new float[]{0.3f,0.8f}, Shader.TileMode.CLAMP));
        canvas.drawArc(mRectf, DefaultDegress, currentDegress, false, mBarPaint);
        canvas.restore();
    }


    int BasePadding=dipToPx(getContext(),8);
    //弧度的背景色
    private void drawBarBg(Canvas canvas) {


        canvas.save();
        canvas.translate(getWidth() / 2, getHeight()/2);
        /*去掉进度条宽度*/
        RectF mRectf = new RectF(-mRadius + mBarWidth / 2, -mRadius + mBarWidth / 2, mRadius - mBarWidth / 2, mRadius - mBarWidth / 2);
        canvas.drawArc(mRectf, DefaultDegress, maxDegress, false, mBarBgPaint);
        canvas.restore();
    }


    /*雷达弧*/
    public void drawRadar(Canvas canvas) {

        canvas.save();
        canvas.translate(getWidth() / 2, getHeight()/2);

        //画扫描
        mRadarPaint.setShader(new SweepGradient(0, 0, new int[]{Color.TRANSPARENT, 0x555C63FA}, new float[]{0.95F, 0.99F}));

        canvas.rotate(DefaultDegress + currentDegress);
        RectF mRect = new RectF(-mRadius + mBarWidth + mRadarMargin, -mRadius + mBarWidth + mRadarMargin, mRadius - mBarWidth - mRadarMargin, mRadius - mBarWidth - mRadarMargin);
        canvas.drawArc(mRect, 0, 360, true, mRadarPaint);

        canvas.restore();
    }


    ValueAnimator mValueAnimator;
    int  mValues=0;
    public void setValues(final int values, boolean isAnm) {

        mValues=values;
        if (isAnm) {


            if (mValueAnimator != null) {
                mValueAnimator.cancel();
                mValueAnimator.setIntValues(0, values);
                mValueAnimator.start();
            } else {
                mValueAnimator = ValueAnimator.ofInt(0, values);
                mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {

                        int animatedValue = (int) animation.getAnimatedValue();
                        currentDegress = (maxDegress-DefaultDegress)*animatedValue/100;
                        currentSorce=animatedValue;
                        postInvalidate();

                    }
                });
                mValueAnimator.setDuration(3000);
                mValueAnimator.start();

            }
        } else {
            currentDegress = values;

            postInvalidate();

        }
    }

    @Override
    public void onClick(View v) {
        if (mValueAnimator.isRunning()) {
            return;
        } else {
            mValueAnimator.start();
        }
    }

    /**
     * dip 转换成px
     *
     * @param dip
     * @return
     */
    public static int dipToPx(Context context, float dip) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f * (dip >= 0 ? 1 : -1));
    }
}
